/***************************************************************************
*                                                                         *
*   This file is part of the Fotowall project,                            *
*       http://code.google.com/p/fotowall                                 *
*                                                                         *
*   Copyright (C) 2007-2009 by Tanguy Arnaud <arn.tanguy@gmail.com>       *
*                                                                         *
*   This program is free software; you can redistribute it and/or modify  *
*   it under the terms of the GNU General Public License as published by  *
*   the Free Software Foundation; either version 2 of the License, or     *
*   (at your option) any later version.                                   *
 * ----------------------------------------------------------------------- *
 *																		   *
 *	Modifications for FotoKinect, Spring 2011 by Gianna Badiali,		   *
 *                                                   Gabriel Fernandez,	   *
 *                                                   Kelsey Tripp, and     *
 *                                                   Sam Swarr             *
 *																		   *
 ***************************************************************************/

#include "ExportWizard.h"
#include "ui_ExportWizard.h"
#include "Desk.h"
#include <QDesktopServices>
#include <QDesktopWidget>
#include <QDir>
#include <QFile>
#include <QFileDialog>
#include <QFileInfo>
#include <QMessageBox>
#include <QProcess>
#include <QSettings>
#include <QUrl>
#include <math.h>
#include <iostream>

#if defined(Q_OS_WIN)
#include <windows.h>    // for background changing stuff
#endif

ExportWizard::ExportWizard(Desk * desk)
	: QWizard()
	, m_ui(new Ui::ExportWizard)
	, m_desk(desk)
	, m_nextId(0)
{
	// create and init UI
	m_ui->setupUi(this);
	connect(m_ui->clImage, SIGNAL(clicked()), this, SLOT(slotModeButtonClicked()));

	// set default sizes
	m_ui->saveHeight->setValue(m_desk->height());
	m_ui->saveWidth->setValue(m_desk->width());

	// connect buttons
	connect(m_ui->chooseFilePath, SIGNAL(clicked()), this, SLOT(slotChoosePath()));

	// configure Wizard
	setOptions(NoDefaultButton | NoBackButtonOnStartPage | IndependentPages);
	setPage(PageMode);

	// react to 'finish'
	connect(this, SIGNAL(finished(int)), this, SLOT(slotFinished(int)));
}

ExportWizard::~ExportWizard()
{
	delete m_ui;
}

void ExportWizard::saveImage()
{
	if (m_ui->filePath->text().isEmpty()) {
		QMessageBox::warning(this, tr("No file selected !"), tr("You need to choose a file path for saving."));
		return;
	}
	QString fileName = m_ui->filePath->text();
	printf(fileName.toStdString().c_str());

	// get the rendering size
	QSize imageSize(m_ui->saveWidth->value(), m_ui->saveHeight->value());

	// render the image
	QImage image;
	if (m_ui->ibZoom->isChecked())
		image = m_desk->renderedImage(imageSize, Qt::KeepAspectRatioByExpanding);
	else if (m_ui->ibScaleKeep->isChecked())
		image = m_desk->renderedImage(imageSize, Qt::KeepAspectRatio);
	else
		image = m_desk->renderedImage(imageSize, Qt::IgnoreAspectRatio);

	// rotate image if requested
	if (m_ui->saveLandscape->isChecked()) {
		// Save in landscape mode, so rotate
		QMatrix matrix;
		matrix.rotate(90);
		image = image.transformed(matrix);
	}

	// save image
	if (image.save(fileName) && QFile::exists(fileName)) {
		int size = QFileInfo(fileName).size();
		QMessageBox::information(this, tr("Done"), tr("The target image is %1 bytes long").arg(size));
	} else
		QMessageBox::warning(this, tr("Rendering Error"), tr("Error rendering to the file '%1'").arg(fileName));
}

void ExportWizard::setPage(int pageId)
{
	// adapt buttons
	QList<QWizard::WizardButton> layout;
	layout << QWizard::Stretch << QWizard::BackButton;
	if (pageId >= PageWallpaper && pageId <= PagePrint)
		layout << QWizard::FinishButton;
	layout << QWizard::CancelButton;
	setButtonLayout(layout);

	// change page
	m_nextId = pageId;
	next();
}

int ExportWizard::nextId() const
{
	// dynamic page ordering
	const int pageId = currentId();

	// mode selection: return the id of the next page (set by the linkbuttons)
	if (pageId == PageMode)
		return m_nextId;

	// final pages
	if (pageId >= PageWallpaper && pageId <= PagePrint)
		return -1;

	// fallback
	qWarning("ExportWizard::nextId: unhandled nextId for page %d", pageId);
	return -1;
}

void ExportWizard::slotChoosePath()
{
	QString fileName = QFileDialog::getSaveFileName(this, tr("Choose the Image file"), m_ui->filePath->text(), tr("Images (*.jpeg *.jpg *.png *.bmp *.tif *.tiff)"));
	if(fileName.isEmpty()) return;
	if (QFileInfo(fileName).suffix().isEmpty())
		fileName += ".png";
	m_ui->filePath->setText(fileName);
}


void ExportWizard::slotFinished(int code)
{
	if (code == QDialog::Accepted) {
		switch (currentId()) {
		case PageImage: saveImage(); break;
		default:
			qWarning("ExportWizard::slotFinished: unhndled end for page %d", currentId());
			break;
		}
	}
}

void ExportWizard::slotModeButtonClicked()
{
	setPage(sender()->property("nextPageId").toInt());
}

void ExportWizard::slotOpenLink(const QString & address)
{
	QDesktopServices::openUrl(QUrl(address));
}
